package com.mys2sh.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public abstract class DESCryptor {

	private static final String ALGORITHM_DES = "DES";

	public static SecretKey genKey(String key) {
		SecretKey deskey = null;
		try {
			SecureRandom secureRandom = new SecureRandom();
			secureRandom.setSeed(key.getBytes());
			KeyGenerator keygen = KeyGenerator.getInstance(ALGORITHM_DES);
			keygen.init(secureRandom);
			deskey = keygen.generateKey();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return deskey;
	}

	public static String encryptor(String content, String key) {
		byte[] cipherByte = null;
		try {
			SecretKey deskey = genKey(key);
			Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
			cipher.init(Cipher.ENCRYPT_MODE, deskey);
			cipherByte = cipher.doFinal(content.getBytes());
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Hex.byte2hex(cipherByte);
	}

	public static String decryptor(String code, String key) {
		byte[] cipherByte = null;
		try {
			SecretKey deskey = genKey(key);
			Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
			cipher.init(Cipher.DECRYPT_MODE, deskey);
			cipherByte = cipher.doFinal(Hex.hex2byte(code));
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return new String(cipherByte);
	}

}
